require "config-biz"

packets = {}


uuid1s = {"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20"}
uuid2s = {"01","02","03","04","05","06","07","08","09"}
index1 = 0;
index2 = 0;
heardTimer = nil


function handler(s, data, port, ip) -- port ip nil
    print("received:"..data)
    t = cjson.decode(data)
    if(t["type"] == "ack")
    then
        if(t["to"] == self) then
            packets[t["uuid"]] = nil
        end 
        return
    end
    if(t["to"] == self) then
        if(t["action"] == "gpioOn") then 
            local pin= t["pin"]
            gpio.mode(pin, gpio.OUTPUT)
            gpio.write(pin, gpio.HIGH)
            local ack = __getInitAck("gpioOn", t["uuid"])
            __sendAck(ack)
        elseif(t["action"] == "gpioOff") then 
            local pin= t["pin"]
            gpio.mode(pin, gpio.OUTPUT)
            gpio.write(pin, gpio.LOW)
            local ack = __getInitAck("gpioOff", t["uuid"])
            __sendAck(ack)
        elseif(t["action"] == "updateWifiConfig") then
            local ack = __getInitAck("updateWifiConfig", t["uuid"])
            if(string.len(t["password"]) < 8) then
                ack.ExcResultCode = "1000"
                ack.ExcResultMsg = "password.len() >= 8"
            else
                updateWifiConfig(t["ssid"], t["password"])
            end
            __sendAck(ack)
        elseif(t["action"] == "getConfigs") then 
            local ack = __getInitAck("getConfigs", t["uuid"])
            ack["configs"] = __getAllConfig()
            __sendAck(ack)
        end
    end
end

function heartTmr()
    heardTimer = tmr.create()
    heardTimer:register(300000, tmr.ALARM_AUTO, heart)
    heardTimer:start()
end

function heart()
    local uuidTmp = getUuid()
    local msg = {}
    msg.from = self
    msg.uuid = uuidTmp
    msg.type = "req"
    msg.to = "netgate"
    msg.action = "heart"
    __sendReq(uuidTmp, cjson.encode(msg), true)
end

function __sendRegister() 
    print("__sendRegister")
    local uuidTmp = getUuid()
    local msg = {}
    msg.from = self
    msg.uuid = uuidTmp
    msg.type = "req"
    msg.to = "netgate"
    msg.action = "register"
    __sendReq(uuidTmp, cjson.encode(msg), true)
end


function __sendReq(uuid, data, first)
    if(first) 
    then 
        packets[uuid] = {["data"] = data, ["time"] = 5}
    else
        packets[uuid]["time"] = packets[uuid]["time"] - 1
        print(string.format(" time = %d", packets[uuid]["time"]))
        if(packets[uuid]["time"] <= 0)
        then
            print("uuid="..uuid.." data="..packets[uuid]["data"].." no response, stop!")
            return
        end
    end
    local mytimer = tmr.create()
    mytimer:register(10000, tmr.ALARM_SINGLE, function() __timeout(uuid, data) end)
    mytimer:start()

    if(isListen)
    then
        conn:send(data)
    end
 end

 function __timeout(uuid, data)
    if(packets[uuid] == nil)
    then 
        return;
    else
        __sendReq(uuid, data, false)
    end
end

function __getInitAck(action, uuid)
    local msg = {}
    msg.from = self
    msg.ExcResultCode = "0000"
    msg.uuid = uuid
    msg.type = "ack"
    msg.to = "netgate"
    msg.action = action
    return msg
end 

function __sendAck(msg)
    if(isListen)
    then
        data = cjson.encode(msg)
        print("sendAck="..data)
        conn:send(data)
    end
end

function getUuid() 
    if(index1 == nil) then
        index1 = 0
    end
    if(index2 == nil) then
        index2 = 0
    end
    index1 = index1 + 1
    if(index1 > 20) then
        index1 = 1
    end
    index2 = index2 + 1
    if(index2 > 9) then
        index2 = 1
    end
    local uuid1 = uuid1s[index1]
    local uuid2 = uuid2s[index2]
    return uuid1..uuid2
end
